package com.formula.distribution.limit.aspect;

import com.formula.distribution.limit.algorithm.RateLimitAlgorihm;
import com.formula.distribution.limit.annotation.RateLimit;
import com.formula.distribution.limit.utils.RateLimitUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author:bo
 * @email:
 * @date 2018/12/14 10:52
 * @introduce @RateLimit的切面
 **/
@Slf4j
@Component
@Aspect
public class RateLimitAspect {


    @Autowired
    private RateLimitAlgorihm rateLimitAlgorihm;


    @Pointcut("@annotation(rateLimit)")
    public void annotationPoinCut(RateLimit rateLimit) {

    }


    @Before("annotationPoinCut(rateLimit)")
    public void doBefore(JoinPoint joinPoint, RateLimit rateLimit) {

        String key = RateLimitUtils.getRateKey(joinPoint, rateLimit.rateLimitType());
        rateLimitAlgorihm.handler(key, rateLimit.limit(), rateLimit.refreshInterval(), rateLimit.tokenBucketStepNum(), rateLimit.tokenBucketTimeInterval(), rateLimit.message());
    }


}
